#include <stdio.h>
#include "timer.h"
#include "esp_log.h"

#define TAG "timer"

static volatile gptimer_handle_t timer_handle;

esp_err_t timer_init(gptimer_alarm_cb_t *callback)
{
    esp_err_t ret;
    gptimer_config_t config = {
        .clk_src = GPTIMER_CLK_SRC_DEFAULT,
        .direction = GPTIMER_COUNT_UP,
        .resolution_hz = 1000000  // 1MHz = 1us精度
    };
    // 1. 创建定时器
    ret = gptimer_new_timer(&config, &timer_handle);
    if (ret == ESP_OK)
    {
        ESP_LOGI(TAG, "timer init success");
    } else {
        ESP_LOGE(TAG, "timer init failed %s", esp_err_to_name(ret));
        gptimer_del_timer(timer_handle);
        return ret;
    }

    // 2. 设置报警值（触发周期）
    gptimer_alarm_config_t alarm_config = {
        .reload_count = 0,
        .alarm_count = 1000, // 1000us = 1ms触发一次
        .flags.auto_reload_on_alarm = true
    };
    gptimer_set_alarm_action(timer_handle, &alarm_config);

    // 3. 注册回调
    gptimer_event_callbacks_t callback_config = {
        .on_alarm = callback
    };
    ret = gptimer_register_event_callbacks(timer_handle, &callback_config, NULL);
    if (ret == ESP_OK)
    {
        ESP_LOGI(TAG, "timer register event callbacks success");
    } else {
        ESP_LOGE(TAG, "timer register event callbacks failed %s", esp_err_to_name(ret));
        gptimer_del_timer(timer_handle);
        return ret;
    }

    // 4. 启用定时器
    ret = gptimer_enable(timer_handle);
    if (ret == ESP_OK)
    {
        ESP_LOGI(TAG, "timer enable success");
    } else {
        ESP_LOGE(TAG, "timer enable failed %s", esp_err_to_name(ret));
        gptimer_del_timer(timer_handle);
        return ret;
    }

    // 5. 启动定时器
    ret = gptimer_start(timer_handle);
    if (ret == ESP_OK)
    {
        ESP_LOGI(TAG, "timer start success");
    } else {
        ESP_LOGE(TAG, "timer start failed %s", esp_err_to_name(ret));
        gptimer_disable(timer_handle);
        gptimer_del_timer(timer_handle);
        return ret;
    }

    return ESP_OK;
}

esp_err_t timer_deinit(void)
{
    if (timer_handle == NULL) {
        return ESP_ERR_INVALID_STATE;
    }
    
    esp_err_t ret = ESP_OK;
    
    // 停止定时器
    ret = gptimer_stop(timer_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "timer stop failed: %s", esp_err_to_name(ret));
    }
    
    // 禁用定时器
    ret = gptimer_disable(timer_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "timer disable failed: %s", esp_err_to_name(ret));
    }
    
    // 删除定时器
    ret = gptimer_del_timer(timer_handle);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "timer delete failed: %s", esp_err_to_name(ret));
    } else {
        timer_handle = NULL;
        ESP_LOGI(TAG, "timer deinitialized successfully");
    }
    
    return ret;
}